/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package towerdefence.view;

import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureCoords;
import javax.media.opengl.GL;
import net.phys2d.math.ROVector2f;
import net.phys2d.raw.Body;
import net.phys2d.raw.shapes.Box;
import static javax.media.opengl.GL.*;

/**
 *
 * @author Andreas
 */
class GLBoxRenderer {

    protected static void drawBox(GL gl, Body body, Box box, float[] color, Texture texture) {
        ROVector2f size = box.getSize();
        ROVector2f position = body.getPosition();
        float halfWidth = size.getX() / 2;
        float halfHeight = size.getY() / 2;

        gl.glPushMatrix();
        gl.glColor4fv(color, 0);
        gl.glTranslatef(position.getX(), position.getY(), 0);
        gl.glRotatef(GLCore.toDegrees(body.getRotation()), 0, 0, 1.0f);


        if (texture == null) {

            gl.glBegin(GL_QUADS);
            {
                gl.glVertex2f(-halfWidth, -halfHeight);
                gl.glVertex2f(halfWidth, -halfHeight);
                gl.glVertex2f(halfWidth, halfHeight);
                gl.glVertex2f(-halfWidth, halfHeight);
            }
            gl.glEnd();

        } else {
            texture.enable();
            texture.bind();
            texture.setTexParameteri(GL_TEXTURE_WRAP_S, GL_REPEAT);
            texture.setTexParameteri(GL_TEXTURE_WRAP_T, GL_REPEAT);

            TextureCoords coords = texture.getImageTexCoords();
            float left = coords.left();
            float top = coords.top();
            float right = coords.right() * size.getX() / texture.getImageWidth();
            float bottom = coords.bottom() * size.getY() / texture.getImageHeight();

            gl.glBegin(GL_QUADS);
            {
                gl.glTexCoord2f(left, top);
                gl.glVertex2f(-halfWidth, -halfHeight);
                gl.glTexCoord2f(right, top);
                gl.glVertex2f(halfWidth, -halfHeight);
                gl.glTexCoord2f(right, bottom);
                gl.glVertex2f(halfWidth, halfHeight);
                gl.glTexCoord2f(left, bottom);
                gl.glVertex2f(-halfWidth, halfHeight);
            }
            gl.glEnd();
            texture.disable();
        }
        gl.glColor3f(0.0f, 0.0f, 0.0f);
        gl.glBegin(GL_LINE_STRIP);
        {
            gl.glVertex2f(-halfWidth, -halfHeight);
            gl.glVertex2f(halfWidth, -halfHeight);
            gl.glVertex2f(halfWidth, halfHeight);
            gl.glVertex2f(-halfWidth, halfHeight);
            gl.glVertex2f(-halfWidth, -halfHeight);
        }
        gl.glEnd();

        gl.glPopMatrix();
    }
}
